package com.meeting.exception;

import com.meeting.common.result.ArgsErrorResult;
import com.meeting.common.result.Result;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.UnexpectedTypeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 *
 */
@Hidden // swagger会和@RestControllerAdvice冲突,需加上@Hidden
@RestControllerAdvice(basePackages = {"com.meeting.controller"})
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception e) {
        log.error("exception", e);
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public Result<String> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        return Result.fail(e.getMessage(), e.getCode());
    }

    // 捕获参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ArgsErrorResult handleValidationException(MethodArgumentNotValidException ex) {
        List<ArgsErrorResult.FieldErrorDetail> errors = ex.getBindingResult().getFieldErrors()
                .stream()
                .map(error -> new ArgsErrorResult.FieldErrorDetail(
                        error.getField(),
                        error.getDefaultMessage())) // 直接使用注解中的message
                .collect(Collectors.toList());

        ArgsErrorResult result = new ArgsErrorResult(
                false,
                HttpStatus.BAD_REQUEST.value(),
                "参数校验失败",
                errors);

        return result;
    }

    @ExceptionHandler(UnexpectedTypeException.class)
    public ArgsErrorResult handleUnexpectedTypeException(UnexpectedTypeException e) {
        log.error("UnexpectedTypeException", e);
        return new ArgsErrorResult(false, HttpStatus.BAD_REQUEST.value(), "参数类型错误", null);
    }
}
